package com.sunflower.common.core.domain.model;

import cn.hutool.core.util.ObjectUtil;
import com.sunflower.common.core.interceptor.SFunction;
import lombok.Data;

import java.io.Serializable;
import java.util.Optional;

/**
 * TODO
 *
 * @author: SunLuQuan
 * @Date: 2024年04月01日 16:21
 * @Description: AbstractToTreeInfo
 */
@Data
public class SimpleToTreeInfo<T> implements ToTreeInfo<T> {

    private SFunction<T, Serializable> parentSFun;

    private SFunction<T, Serializable> idSFun;

    private SFunction<T, Serializable> nameSFun;

    public SimpleToTreeInfo(SFunction<T, Serializable> parentSFun, SFunction<T, Serializable> idSFun, SFunction<T, Serializable> nameSFun) {

        this.parentSFun = parentSFun;
        this.idSFun = idSFun;
        this.nameSFun = nameSFun;
    }

    public SimpleToTreeInfo(SFunction<T, Serializable> parentSFun, SFunction<T, Serializable> idSFun) {

        this(parentSFun, idSFun, null);
    }

    /**
     * 父级属性
     *
     * @return
     */
    @Override
    public SFunction<T, Serializable> parentId() {
        return parentSFun;
    }

    /**
     * 子级属性
     *
     * @return
     */
    @Override
    public SFunction<T, Serializable> id() {
        return idSFun;
    }

    /**
     * 树节点名称
     *
     * @return
     */
    @Override
    public SFunction<T, Serializable> name() {
        return nameSFun;
    }

    /**
     * 是否是根节点
     *
     * @param t
     * @return
     */
    @Override
    public boolean condition(T t) {
        return ObjectUtil.isEmpty(idSFun.apply(t));
    }

    /**
     * 转换为Tree对象
     *
     * @param t
     * @return
     */
    @Override
    public Tree<T> toTree(Tree<T> parent, T t) {
        Tree<T> tTree = new Tree<>();
        tTree.setData(t);
        tTree.setValue(idSFun.apply(t));
        Optional.ofNullable(parent)
            .ifPresent(item -> {
                tTree.setParent(item);
                Optional.ofNullable(item.getData())
                    .ifPresent(data -> tTree.setParentId(idSFun.apply(data)));
            });
        Optional.ofNullable(nameSFun).ifPresent(item -> tTree.setName(item.apply(t)));
        return tTree;
    }
}
